package com.zzy.test.config;

import com.zzy.test.emailLogin.EmailCodeAuthenticationFailureHandler;
import com.zzy.test.emailLogin.EmailCodeAuthenticationFilter;
import com.zzy.test.emailLogin.EmailCodeAuthenticationProvider;
import com.zzy.test.emailLogin.EmailCodeAuthenticationSuccessHandler;
import com.zzy.test.service.EmailCodeUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

/**
 * @author Lucas-zhang
 * @description TODO
 * @date 2022-03-21 12:03
 */
@Component
public class EmailCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    // 注入email验证服务
    @Autowired
    private EmailCodeUserDetailsService emailCodeUserDetailsService;

    @Override
    public void configure(HttpSecurity http) {
        // 配置Filter
        EmailCodeAuthenticationFilter emailCodeAuthenticationFilter = new EmailCodeAuthenticationFilter();
        // 设置AuthenticationManager
        emailCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        // 设置认证成功处理Handler
        emailCodeAuthenticationFilter.setAuthenticationSuccessHandler(new EmailCodeAuthenticationSuccessHandler());
        // 设置认证失败处理Handler
        emailCodeAuthenticationFilter.setAuthenticationFailureHandler(new EmailCodeAuthenticationFailureHandler());

        // 配置Provider
        EmailCodeAuthenticationProvider emailCodeAuthenticationProvider = new EmailCodeAuthenticationProvider();
        // 设置email验证服务
        emailCodeAuthenticationProvider.setEmailCodeUserDetailsService(emailCodeUserDetailsService);

        // 将过滤器添加到过滤器链路中
        http.authenticationProvider(emailCodeAuthenticationProvider).addFilterAfter(emailCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
